import {
	d_uniShowToast,
	TOKEN_key
} from './misc';
import {
	uniGetStorageSync,
	exitLogin,
	uniConfigRight,
} from './funcs';
import {
	USER_ORIENTED
} from './config';
import {
	ENVIRONMENT
} from '@/util/config';


export let ONLINE_SERVER_ADDRESS_BASE = 'http://www.qizu2020.com';
// export let ONLINE_SERVER_ADDRESS_BASE = 'http://testv2.qizu2020.com';
export let ONLINE_SERVER_ADDRESS_BASE_2 = 'http://120.79.137.61:8088';
// export let ONLINE_SERVER_ADDRESS_BASE_2 = 'http://47.106.103.154:8088';
// 设置访问域名
!(function() {
	if (['dev', 'beta', 'development'].includes(ENVIRONMENT)) {
		ONLINE_SERVER_ADDRESS_BASE = 'https://v22.openeast.com';
	}
})();

export const ONLINE_SERVER_USER = ONLINE_SERVER_ADDRESS_BASE + '/api/app';
export const ONLINE_SERVER_MERCHANT =
	// ONLINE_SERVER_ADDRESS_BASE + '/api/merchant';
	ONLINE_SERVER_ADDRESS_BASE + '/api/merchant';

export const BASE_API = USER_ORIENTED ?
	ONLINE_SERVER_USER :
	ONLINE_SERVER_MERCHANT;

export function baseApi_(url) {
	return BASE_API + url;
}

export function getHeaderForPost() {
	let token = uniGetStorageSync(TOKEN_key);
	return {
		Authorization: 'Bearer ' + token,
	};
}

/**
 * @description 状态说明
 *  200：正常
 *	400：普通功能级的业务报错（弹窗提示）
 *	201：苹果账号注册需要绑定手机号
 *	401：微信账号注册需要绑定手机号
 *	402：token报错，退出重新登录
 *	403：招商端的接口才会有，提示无操作权限
 *	506：账号异常退出登录
 */
/**
 * @description 不带token的请求封装
 * @param url   请求路由
 * @param data  请求参数 
 * @param met   请求方式
 * @param failCb 额外的方法
 * @param merchant 基础路由 (true: '/api/merchant',false: '/api/app')
 */
export function uniRequestP(url, data = '', met = 'POST', merchant = true) {
	return new Promise((resolve, reject) => {
		let baseApi = merchant ? BASE_API : ONLINE_SERVER_USER;
		let finallyUrl = baseApi + url;
		uni.request({
			method: met,
			url: finallyUrl,
			// header: {'Content-Type': "application/x-www-form-urlencoded"},
			data: data,
			success: (res) => {
				if (res.data.code == 200 || res.data.code == 201 || res.data.code == 401) {
					resolve(res.data)
				} else if (res.data.code == 400 || res.data.code == 403) {
					// 400 普通功能级的业务报错（弹窗提示）
					// 403 招商端的接口才会有，提示无操作权限
					d_uniShowToast({
						title: res.data.msg,
					});
					reject()
				} else if (res.data.code == 402 || res.data.code == 506) {
					// 402 token报错，退出重新登录
					// 506 账号异常退出登录
					exitLogin(res.data.msg);
					reject()
				}
			},
			fail: (res) => {
				d_uniShowToast({
					title: "网络异常",
				});
				console.warn(res.errMsg);
				reject(res);
			},
		});

	})
}

/**
 * @description 带token的请求封装
 * @param url   请求路由
 * @param data  请求参数 
 * @param met   请求方式
 * @param showToast  未登录时,是否显示提示
 * @param failCb 额外的方法
 * @param merchant 基础路由 (true: '/api/merchant',false: '/api/app')
 */
export function tokenRequestP(url, data = '', met = 'POST', showToast = false, failCb, merchant = true) {
	return new Promise((resolve, reject) => {
		let token = uniGetStorageSync(TOKEN_key);
		// 判断是否登录
		if (!checkLogin(token, showToast, failCb)) return
		let header = {
			Authorization: 'Bearer ' + token
		};
		let baseApi = merchant ? BASE_API : ONLINE_SERVER_USER;
		let finallyUrl = baseApi + url;

		uni.request({
			method: met,
			url: finallyUrl,
			header: header,
			data: data,
			success: (res) => {
				if (res.data.code == 200 || res.data.code == 201 || res.data.code == 401) {
					// 201 苹果账号注册需要绑定手机号
					// 401 微信账号注册需要绑定手机号
					resolve(res.data)
				} else if (res.data.code == 400 || res.data.code == 403) {
					// 400 普通功能级的业务报错（弹窗提示）
					// 403 招商端的接口才会有，提示无操作权限
					d_uniShowToast({
						title: res.data.msg,
					});
					reject()
				} else if (res.data.code == 402 || res.data.code == 506) {
					// 402 token报错，退出重新登录
					// 506 账号异常退出登录
					exitLogin(res.data.msg);
					reject()
				}
			},
			fail: (res) => {
				// res.errMsg (request:fail,request:fail timeout)
				d_uniShowToast({
					title: "网络异常",
				});
				console.warn(res.errMsg);
				reject(res);
			}
		})
	})
}

/**
 * @description 判断是否登录
 * @param {Object} showToast 是否显示提示
 * @param {Object} failCb    额外的函数
 */
function checkLogin(token, showToast, failCb) {
	if (!token) {
		if (showToast) {
			d_uniShowToast({
				title: '请先登录',
			});
		}
		failCb && failCb();
		return false
	}
	return true
}

/**
 * @description 判断请求返回的code
 * @param {Object} res 返回的参数
 */
function judgeCode(res) {
	if (res.data.code == 200) {
		return res.data
	}
}

// 以下代码未来将不再使用，但留着先

export function uniRequest(url, postData, opt, isLocalDev, isCommon) {
	let finalUrl = BASE_API + url;
	// console.log('POST: ',finalUrl);
	uni.request({
		method: 'POST',
		url: finalUrl,
		data: postData,
		...opt,
	});
}

export function proRequest(url, postData, option) {
	return new Promise((resolve, reject) => {
		uniRequest(url, postData, {

			success: ({
				data
			}) => {
				if (data.code === 200) {
					resolve(data);
				} else {
					reject(data);
				}
			},
			...option,
		});
	});
}

// token不是必需品的post
export function optionalTokenRequest(url, otherPostData, opt) {
	// 招商人员所有页面必须要token
	let token = uniGetStorageSync(TOKEN_key);
	if (!token) {
		console.warn('未登录');
		uniRequest(url, otherPostData, opt);
		return;
	}
	tokenRequest(url, otherPostData, opt);
}

export function tokenRequest(
	url,
	postData,
	opt,
	showToast = false,
	failCb
) {
	let token = uniGetStorageSync(TOKEN_key);
	// console.log('requesting')
	if (!token) {
		// console.warn('未登录');
		if (showToast) {
			d_uniShowToast({
				title: '请先登录',
			});
		}
		failCb && failCb();
	}
	let header = {
		Authorization: 'Bearer ' + token
	};
	uni.request({
		header: header,
		url: BASE_API + url,
		method: 'POST',
		success: (res) => {
			console.log("dengluceshi",res)
		},
		fail: (res) => {
			//
			console.log('failed request: ' + url, ' ', header, res);
		},
		data: postData,
		...opt,
	});
}
async function myUploadFile(token, ofile) {
	let imgId = -1
	// const a = await pathToBase64(ofile);
	// console.log("文件pathToBase64为：",a)
	// console.log("[info]","正在上传文件" + a + "token:" + token)
	const res = await uni.uploadFile({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/file/upload`, //仅为示例，非真实的接口地址
		filePath: ofile,
		name: 'file',
		formData: {
			'user': 'test'
		},
		header: {
			// 'content-type': 'application/json',
			'Authorization': token,
			// 'content-type': 'multipart/form-data',
		},
	});	
	const [err,{data}] = res;
	console.log("文件res为：",JSON.parse(data))
	let result = JSON.parse(data)
	imgId = result.data
    return new Promise((resolve, reject) => {
            resolve(imgId)
    })
}

async function myDownloadFile(token, fileId) {
	let imgId = -1
	token = uni.getStorageSync('token')
	console.log("[info]","正在下载文件：" + fileId + "token:" + token)
	const res = await uni.downloadFile({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/file/download` + fileId, //仅为示例，非真实的接口地址
		header: {
			'Authorization': token,
		},
	});	
	console.log("文件res为：",res[1])
    return new Promise((resolve, reject) => {
            resolve(res[1].tempFilePath)
    })
}

async function syncGetOrder(url) {
	let token = uni.getStorageSync('token')
	const res = await uni.request({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/` + url, //仅为示例，非真实的接口地址
		header: {
			'Authorization': token,
		},
		method:'GET',
	});	
	console.log("异步结果：",res[1])
    return new Promise((resolve, reject) => {
            resolve(res[1])
    })
}

async function syncGetOrderList(url, state, pageNo, pageSize) {
	let token = uni.getStorageSync('token')
	const res = await uni.request({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/` + url, //仅为示例，非真实的接口地址
		header: {
			'Authorization': token,
		},
		method:'GET',
		data:{
			pageNo:pageNo,
			pageSize:pageSize,
			status: state
		},
	});	
	console.log("异步结果：",res[1])
    return new Promise((resolve, reject) => {
            resolve(res[1])
    })
}

async function syncGetGoodsList(url, state, pageNo, pageSize, area) {
	let token = uni.getStorageSync('token')
	const res = await uni.request({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/` + url, //仅为示例，非真实的接口地址
		header: {
			'Authorization': token,
		},
		method:'GET',
		data:{
			area:area,
			pageNo:pageNo,
			pageSize:pageSize,
			status: state
		},
	});	
	console.log("异步结果：",res[1])
    return new Promise((resolve, reject) => {
            resolve(res[1])
    })
}

async function syncGoodsInfo(url) {
	let token = uni.getStorageSync('token')
	const res = await uni.request({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/` + url, //仅为示例，非真实的接口地址
		header: {
			'Authorization': token,
		},
		method:'GET',
	});	
	console.log("异步结果：",res[1])
    return new Promise((resolve, reject) => {
            resolve(res[1])
    })
}

async function syncGetSysUsr(url,areaId,roleId) {
	let token = uni.getStorageSync('token')
	const res = await uni.request({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/` + url, //仅为示例，非真实的接口地址
		header: {
			'Authorization': token,
		},
		data: {
			areaId:areaId,                      //操作信息
			authId:roleId,
		},
		method:'POST',
	});	
	console.log("异步结果：",res[1])
    return new Promise((resolve, reject) => {
            resolve(res[1])
    })
}

async function syncGetSysUsrInfo(url) {
	let token = uni.getStorageSync('token')
	const res = await uni.request({
		url: `${ONLINE_SERVER_ADDRESS_BASE_2}/` + url, //仅为示例，非真实的接口地址
		header: {
			'Authorization': token,
		},
		method:'GET',
	});	
	console.log("异步结果userinfo：",res[1])
    return new Promise((resolve, reject) => {
            resolve(res[1])
    })
}

export function getUserRight(userId,auth_type){
	let token = uni.getStorageSync('token')
	uni.request({
		url:`${ONLINE_SERVER_ADDRESS_BASE_2}/systemuser/user-auth/` + userId,
		header: {
			'Authorization': token,
		},
		method:'GET',
		success: function (res) {
			if(res.data.code == 200){
				uniConfigRight(res.data.data.authList,auth_type)
			}
			console.log("查询user权限成功",res.data);
		}
	})
}

export function uniRedirect(url, cb) {
	uni.redirectTo({
		url: '/pages' + url,
		success: (res) => {
			cb && cb();
		},
		fail: function(res) {
		},
	});
}

export {
	myUploadFile,
	myDownloadFile,
	syncGetOrder,
	syncGetOrderList,
	syncGetGoodsList,
	syncGoodsInfo,
	syncGetSysUsr,
	syncGetSysUsrInfo,
}
